package rsj.service.usage.org;

import com.rlyy.aibase.utils.base.Node;
import com.rlyy.aibase.utils.base.TableNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import rsj.api.org.entity.CurrentTableColumn;
import rsj.api.org.entity.UsageReportParam;
import rsj.sql.org.UsageProduceReportForOrgDao;
import rsj.service.export.org.IOrgExportCurrentTable;
import rsj.service.usage.IUsageTemplateMethod;

import java.util.List;
import java.util.Objects;
import java.util.stream.Stream;

/**
 * 机构管理-生产环境客户使用情况
 *
 * @author yuanqinglong
 * @since 2021/3/3 16:52
 */
@Component
public class UsageProduceReportForOrg implements IOrgCalculateUsage, IUsageTemplateMethod {


    @Autowired
    private UsageProduceReportForOrgDao usageProduceReportForOrgDao;


    /**
     * 统计总数
     *
     * @param usageReportParam 参数
     * @return {@link Node}
     */
    @Override
    public Node countStatistic(UsageReportParam usageReportParam) {
        return usageProduceReportForOrgDao.countStatistic(usageReportParam);
    }


    /**
     * 出口产品当前表
     *
     * @param usageReportParam 出口参数
     * @return {@link TableNode}
     */
    @Override
    public TableNode queryTableByPage(UsageReportParam usageReportParam) {
        return usageProduceReportForOrgDao.queryTableByPage(usageReportParam);
    }





    /**
     * 生成查询sql
     *
     * @param usageReportParam 参数
     * @return sql
     */
    @Override
    public String generateQueryStatement(UsageReportParam usageReportParam) {
        String sql = IOrgExportCurrentTable.exportCurrentTableQueryStatement(usageReportParam);
        sql += " LIMIT " + usageReportParam.getPageSize() + " OFFSET " + usageReportParam.getPageNow();
        return sql;

    }


    /**
     * 生成统计总数sql
     *
     * @param usageReportParam 参数
     * @return sql
     */
    @Override
    public String generateCountStatement(UsageReportParam usageReportParam) {
        String countSql = "SELECT COUNT(*) FROM (" + IOrgExportCurrentTable.exportCurrentTableQueryStatement(usageReportParam) + ") a";
        return countSql;
    }


    /**
     * 计算生产环境产品剩余量
     *
     * @param statisticColumnEntities 使用量列表数据（包含购买量和使用量、未计算剩余量）
     */
    @Override
    public void ifYouNeedToCalculateTheRemainingAmount(List<CurrentTableColumn> statisticColumnEntities) {
        statisticColumnEntities.forEach(currentTableColumn -> {
            int sumOfUsage = Stream.of(currentTableColumn.getStatUseamount().split(",")).mapToInt(Integer::parseInt).sum();
            currentTableColumn.setStatRemainder(String.valueOf(currentTableColumn.getOrgpBuyamount() - sumOfUsage));
        });
    }
}
